window.addEvent('domready', function() {
	chat.addExt({
		ini: function(){
			this.commands = {}; //Have all command-funtion in list.
			this.commandPending = {};
		}
	
		/*
		Add new command to the command list.
		commandDef have the form: {
			r : COMMANDID, //request
			fun: COMMANDFUN(command) //if the command is an output command :: needs confirmation, but not data.
			,answerFun: COMMANDANSWERFUN(command) //if the command is an input command.
		}
		*/
		,addNewCommand: function(commandDef){
			if( !this.checkCommand(commandDef.r) ){
				this.commands[commandDef.r] = {
					fun : (commandDef.fun) ? commandDef.fun : this.makeAnswer
					,answerFun: commandDef.answerFun
				};
			} else {	
				console.log("Error adding new command. Command duplicated.");
			}
		}
	
		//Check if a command is into command list.
		,checkCommand: function(request){
			if( request && this.commands[request] ) return true;
			else return false;
		}
	
		/*All command object have the form:
			c : {
				r : COMMANDID, //request
				idc: IDCOMMAND
				, (....)
			}
		*/
		,executeCommand: function(command){
			if( this.checkCommand(command.r) )
				var answer = this.commands[command.r].fun.bind(this, command)();
			else
				var answer = this.makeAnswer(command);
			return answer;
		}
		,processAnswer: function(answer){
			if( this.commandPending[answer.idc] ) {
				this.commands[this.commandPending[answer.idc].r].answerFun.bind(this, answer)();
				delete this.commandPending[answer.idc];
			} else
				console.log("Respuesta desconocida.");
		}
	
		//return a valid answer object. If answer is false or null it is considered a failed answer.
		,makeAnswer: function(command, answer){
			if(!answer) return {idc: command.idc , 'answer' : 'fail'};
			else return {idc: command.idc , 'answer' : answer};
		}
		,makeAndSendCommand: function(request, args){
			var l = Object.getLength(this.commandPending);
			var command = {r: request, idc: l, 'args': args};
			this.commandPending[l] = command; //Save the command in pending commands for an answer.
		
			this.sendCommand(command);
		}
	});
});
